<script lang="ts" setup>
import FeedbackDialog from './components/feedback-dialog/index.vue'
import ListItem from './components/list-item/index.vue'
import { RecommendReply, RecommendStatus, RecommendUpdates } from '@/models/recommend'
import NotData from '@/components/NotData.vue'
import { Status } from '@/models/sys'
import useExposureViewList from '@/hooks/useExposureViewList'
import { checkLatestRecommendReply } from '@/service/index/recommend'
import _ from 'lodash'

const props = withDefaults(
  defineProps<{
    isTab: boolean
    isCheck: boolean
    status: RecommendStatus
  }>(),
  {},
)

watch(
  () => props.isTab,
  (val) => {
    if (val) {
      refresh()
      openMessageSubscribe()
    } else {
      messageSubscribe.stop()
    }
  },
)

watch(
  () => props.isCheck,
  (val) => {
    if (val) {
      refresh()
      openMessageSubscribe()
    }
  },
)

const messageSubscribe = useMessageSubscribe()
openMessageSubscribe()

onUnmounted(() => {
  messageSubscribe.stop()
})

const emit = defineEmits(['badgeUpdate'])
const tipsList = ref<number[]>([])

function openMessageSubscribe() {
  if (props.status === RecommendStatus.Sent) return
  messageSubscribe.start(checkLatestRecommendReply, {
    async onMessage(data: RecommendUpdates) {
      if (data.latest.length) {
        messageParams.value.latest_id = data.latest[0].id
        messageSubscribe.setExtraParams(messageParams.value)
        tipsList.value = tipsList.value.concat(data.latest.map((item) => item.id))
        // 在最前面插入多个数据
        if (listData.value.length) {
          listData.value.unshift(...data.latest)
        } else {
          // refresh()
          paging.value?.reload()
        }
        nextTick(async () => {
          await exposureViewList()
          emit('badgeUpdate', tipsList.value.length)
        })
      }

      if (data.remove_ids.length) {
        // 删除数据
        data.remove_ids.forEach((id) => {
          const index = listData.value.findIndex((item) => item.id === id)
          if (index !== -1) {
            listData.value.splice(index, 1)
          }
        })
      }
    },
    onStop() {},
  })
}

/**
 * 刷新
 */
function refresh() {
  paging.value?.refresh()
}

defineExpose({
  refresh,
  stopSubscribe: () => {
    messageSubscribe.stop()
  },
})

const listData = ref<RecommendReply[]>([])

const exposureView = useExposureViewList()

function scroll() {
  exposureViewList()
}

function exposureViewList() {
  return exposureView.useList(listData.value, (item) => {
    if (!tipsList.value.includes(item.id)) return
    tipsList.value = tipsList.value.filter((id) => id !== item.id)
    // tabState.list[0].badgeProps.modelValue = tipsList.value.length
    emit('badgeUpdate', tipsList.value.length)
  })
}

const { ...callback } = useChat()

const paging = ref()

const messageParams = ref({
  start_id: 0,
  latest_id: 0,
})

async function query(page: number, per_page: number) {
  const listData = await callback.getRecommendReplyList({
    page,
    per_page,
    status: props.status,
  })
  if (page === 1 && listData.length) {
    messageParams.value.start_id = listData[0].id
    messageParams.value.latest_id = listData[0].id
    tipsList.value = []
    emit('badgeUpdate', tipsList.value.length)
    messageSubscribe.setExtraParams(messageParams.value)
  }
  paging.value.complete(listData)
}

/** 打开反馈 */
const feedbackDialogRef = ref<InstanceType<typeof FeedbackDialog>>()

function openClick(item: RecommendReply) {
  feedbackDialogRef.value?.open(item.id)
}

/** 采集好评跳转 */
function suspectedPositiveClick(item: RecommendReply) {
  uni.navigateTo({
    url: `/pages/comment/commentPage?parentId=${item.customer.id}&parentName=${item.customer.display_name}`,
  })
}

/** 发送消息 */
const sendMessage = _.debounce(
  (val) => {
    callback.sendReply({ id: val.id, reply_content: val.reply_content }, () => {
      uni.showToast({
        title: '发送成功',
      })
      refresh()
    })
  },
  500,
  {
    leading: true,
    trailing: false,
  },
)

/** 编辑信息 */
function editReply(val) {
  callback.editReply({ id: val.id, reply_content: val.reply_content }, () => {
    uni.showToast({
      title: '编辑成功',
      icon: 'none',
    })
    refresh()
  })
}

/** 打开对话 */
function openChat(item: RecommendReply) {
  wx.qy.openEnterpriseChat({
    externalUserIds: item.customer.external_user_id,
    userIds: '',
    groupName: '',
    chatId: '',
    success: (res) => {
      console.log(res)
    },
    fail(err) {
      uni.showModal({
        title: '打开失败',
        content: JSON.stringify(err),
        showCancel: false,
        confirmText: '好的',
      })
    },
  })
}

/** 点踩 */
function bad(item: RecommendReply) {
  item.is_bad = item.is_bad ? Status.No : Status.Yes
  callback.dislikeReply({ id: item.id, is_bad: item.is_bad }, () => {
    refresh()
  })
}
</script>

<template>
  <view class="relative pt-2" style="height: 100%">
    <z-paging
      ref="paging"
      loading-more-no-more-text="没有更多了"
      v-model="listData"
      @query="query"
      :fixed="false"
      :default-page-size="20"
      @scroll="scroll"
      auto-show-back-to-top
      show-refresher-when-reload
    >
      <template #empty>
        <NotData text="暂无更多待回复消息"></NotData>
      </template>
      <view
        class="list"
        v-for="item in listData"
        :class="`item_${item.id}`"
        :key="`${item.id}_${props.status}_${item.reply_content.length}`"
      >
        <ListItem
          :itemData="item"
          :status="props.status"
          :key="`${item.id}_${props.status}_${item.reply_content.length}`"
          @feedback="() => openClick(item)"
          @suspected-positive="() => suspectedPositiveClick(item)"
          @send-message="(val) => sendMessage(val)"
          @open-chat="() => openChat(item)"
          @bad="() => bad(item)"
          @editReply="(val) => editReply(val)"
          @streamDone="() => refresh()"
        ></ListItem>
      </view>
      <view class="h-10"></view>
    </z-paging>
    <FeedbackDialog ref="feedbackDialogRef" :refresh="refresh"></FeedbackDialog>
  </view>
</template>

<style lang="scss" scoped>
.scroll-views {
  height: calc(100% - 107rpx);
  margin-top: 15rpx;
}
</style>
